package com.ftcs.controller;

import com.ftcs.model.Msg;
import com.ftcs.service.LoginService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;


@Api(value = "登录登出接口")
@Controller
public class LoginController {
    @Autowired
    LoginService loginservice;

    @PostMapping(value = "/loginvalidate")
    public String loginvalidate(@RequestParam("username") String username, @RequestParam("password") String pwd, HttpSession httpSession) {
        if (username == null) {
            return "login";
        }
        String realpwd = loginservice.getPwdbyName(username);
        if (realpwd != null && pwd.equals(realpwd)) {
            httpSession.setAttribute("username", username);
            return "index";
        } else {
            return "fail";
        }
    }

    @GetMapping(value = "/login")
    public String login() {
        return "login";
    }

    @GetMapping(value = "/logout")
    public String logout(HttpSession httpSession) {
        httpSession.removeAttribute("username");
        return "login";
    }

    @GetMapping(value = "/currentuser")
    @ResponseBody
    public Msg currentuser(HttpSession httpSession) {
        String userid = (String) httpSession.getAttribute("username");
        return new Msg(userid);
    }

}
